/**
 * 项目工时统计分析页面
 */

'use client';

import React, { useState } from 'react';
import { Layout, Space, Typography, Card, Row, Col, Empty, Button } from 'antd';
import { ArrowLeftOutlined, BarChartOutlined, ProjectOutlined } from '@ant-design/icons';
import Link from 'next/link';
import WorkloadStatsFilter from '../../components/WorkloadStatsFilter';
import WorkloadCharts from '../../components/WorkloadCharts';
import ProjectDetailModal from '../../components/ProjectDetailModal';
import { useWorkloadStats } from '../../hooks/useWorkloadStats';
import { calculateWorkloadSummary } from '../../utils/workloadStatsUtils';
import type { WorkloadStatsQueryParams, ProjectWorkloadSummary } from '../../types/workloadStats';

const { Header, Content } = Layout;
const { Title, Text } = Typography;

export default function WorkloadStatsPage() {
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  
  const {
    loading,
    projectSummaries,
    chartData,
    timeSeriesData,
    comparisonData,
    selectedProject,
    projectDetails,
    detailLoading,
    fetchWorkloadStats,
    fetchProjectDetails,
    setSelectedProject
  } = useWorkloadStats();

  const handleSearch = (params: WorkloadStatsQueryParams) => {
    // 如果是重置操作，不执行查询
    if ((params as any).reset) {
      return;
    }
    
    fetchWorkloadStats(params);
  };

  const handleViewProjectDetail = (project: ProjectWorkloadSummary) => {
    setSelectedProject(project);
    fetchProjectDetails(project.projectId, {
      startDate: project.startDate.split('T')[0],
      endDate: project.endDate.split('T')[0]
    });
    setDetailModalVisible(true);
  };

  const handleDetailModalClose = () => {
    setDetailModalVisible(false);
    setSelectedProject(null);
  };

  // 计算汇总统计
  const summary = calculateWorkloadSummary(projectSummaries);

  return (
    <Layout className="min-h-screen bg-gray-50">
      <Header className="bg-white shadow-sm border-b px-6">
        <div className="flex items-center justify-between h-full">
          <Space size="large">
            <Link href="/workloads" className="flex items-center text-gray-600 hover:text-blue-600">
              <ArrowLeftOutlined className="mr-2" />
              返回工时查询
            </Link>
            <Title level={3} className="!mb-0 !text-gray-800">
              <Space>
                <BarChartOutlined />
                项目工时统计分析
              </Space>
            </Title>
          </Space>
        </div>
      </Header>

      <Content className="p-6">
        <div className="max-w-full mx-auto space-y-6">
          {/* 筛选条件 */}
          <WorkloadStatsFilter onSearch={handleSearch} loading={loading} />

          {projectSummaries.length > 0 ? (
            <>
              {/* 概览统计卡片 */}
              <Row gutter={[16, 16]}>
                <Col xs={24} sm={12} md={6}>
                  <Card>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-blue-600">
                        {summary.totalHours.toFixed(1)}
                      </div>
                      <div className="text-gray-500 mt-1">总工时 (小时)</div>
                    </div>
                  </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                  <Card>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-green-600">
                        {summary.totalProjects}
                      </div>
                      <div className="text-gray-500 mt-1">涉及项目</div>
                    </div>
                  </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                  <Card>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-orange-600">
                        {summary.totalMembers}
                      </div>
                      <div className="text-gray-500 mt-1">参与人员</div>
                    </div>
                  </Card>
                </Col>
                <Col xs={24} sm={12} md={6}>
                  <Card>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-purple-600">
                        {summary.avgHoursPerProject.toFixed(1)}
                      </div>
                      <div className="text-gray-500 mt-1">平均项目工时</div>
                    </div>
                  </Card>
                </Col>
              </Row>

              {/* 图表分析 */}
              <WorkloadCharts
                projectSummaries={projectSummaries}
                chartData={chartData}
                timeSeriesData={timeSeriesData}
                comparisonData={comparisonData}
                loading={loading}
                onProjectClick={handleViewProjectDetail}
              />

              {/* 项目工时统计表格 */}
              <Card 
                title={
                  <Space>
                    <ProjectOutlined />
                    <span>项目工时汇总</span>
                    <Text type="secondary">({projectSummaries.length} 个项目)</Text>
                  </Space>
                }
              >
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr className="bg-gray-50">
                        <th className="border p-3 text-left">项目名称</th>
                        <th className="border p-3 text-center">总工时</th>
                        <th className="border p-3 text-center">参与成员</th>
                        <th className="border p-3 text-center">工作天数</th>
                        <th className="border p-3 text-center">平均日工时</th>
                        <th className="border p-3 text-center">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      {projectSummaries.map((project, index) => (
                        <tr key={project.projectId} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                          <td className="border p-3">
                            <div>
                              <div className="font-medium">{project.projectName}</div>
                              <div className="text-sm text-gray-500">{project.projectIdentifier}</div>
                            </div>
                          </td>
                          <td className="border p-3 text-center">
                            <span className="font-bold text-blue-600">
                              {project.totalHours.toFixed(1)}h
                            </span>
                          </td>
                          <td className="border p-3 text-center">
                            <span className="text-green-600">
                              {project.memberCount} 人
                            </span>
                          </td>
                          <td className="border p-3 text-center">
                            {project.workDays} 天
                          </td>
                          <td className="border p-3 text-center">
                            {project.avgDailyHours.toFixed(1)}h
                          </td>
                          <td className="border p-3 text-center">
                            <Button
                              type="link"
                              size="small"
                              onClick={() => handleViewProjectDetail(project)}
                            >
                              查看详情
                            </Button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </Card>
            </>
          ) : (
            <Card>
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={
                  <div>
                    <Text type="secondary">请选择项目和时间范围进行工时统计分析</Text>
                    <br />
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      💡 提示：为了提高查询效率，请先选择具体的项目再进行统计
                    </Text>
                  </div>
                }
              />
            </Card>
          )}

          {/* 项目详情模态框 */}
          <ProjectDetailModal
            visible={detailModalVisible}
            onClose={handleDetailModalClose}
            projectSummary={selectedProject}
            workloadDetails={projectDetails}
            loading={detailLoading}
          />
        </div>
      </Content>
    </Layout>
  );
}